package web.PetStore.web.servlet;

import web.PetStore.domain.Account;
import web.PetStore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static web.PetStore.web.servlet.CaptchaServlet.checkCodeCorrect;

@WebServlet(name = "LoginServlet", urlPatterns = {"/Login"})
public class LoginServlet extends HttpServlet {
    private String userid, password,checkcode;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.userid = req.getParameter("userid");
        this.password = req.getParameter("password");
        this.checkcode = req.getParameter("checkcode");
        HttpSession session = req.getSession();
        if(!this.userid.trim().equals(this.userid)){
            req.setAttribute("loginInfo", "用户名不能包含空格");
            req.getRequestDispatcher("LoginForm").forward(req,resp);
        }else if(this.userid.isEmpty() || this.password.isEmpty()){
            req.setAttribute("loginInfo", "用户名或密码不能为空");
            req.getRequestDispatcher("LoginForm").forward(req,resp);
        }else if(!checkCodeCorrect(checkcode)){
            req.setAttribute("loginInfo" , "验证码错误");
            req.getRequestDispatcher("LoginForm").forward(req,resp);
        }else{
            AccountService accountService = new AccountService();
            Account loginUser = accountService.confirmUserByIdAndPassword(userid, password);
            if(loginUser != null){
                session.setAttribute("loginUser", loginUser);
                resp.sendRedirect("index.jsp");
            }else{
                req.setAttribute("loginInfo" , "用户名或密码错误");
                req.getRequestDispatcher("LoginForm").forward(req,resp);
            }
        }
    }
}